mod sip_handler;
mod rtp_handler;
mod audio_io;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    net::SocketAddr,
    sync::{Arc, Mutex},
    time::Duration,
    io::Write,
};
use tokio::{
    net::{TcpListener, TcpStream},
    sync::mpsc,
    time::timeout,
    io::{AsyncReadExt, AsyncWriteExt},
};
use tracing::{error, info, warn, debug};

use sip_handler::{SipMessageHandler, SipTransaction, SipTransactionState, SipRequest, SipResponse, AuthInfo, SdpInfo};
use rtp_handler::AudioProcessor;
use audio_io::{AudioIO, f32_to_pcmu, pcmu_to_f32};

#[derive(Parser)]
#[command(name = "freeswitch-sip-cli")]
#[command(about = "FreeSWITCH SIP客户端")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// 启动SIP客户端服务器
    Start {
        /// 本地监听端口
        #[arg(short, long, default_value = "5060")]
        port: u16,
        /// FreeSWITCH服务器地址
        #[arg(short, long, default_value = "127.0.0.1")]
        server: String,
        /// FreeSWITCH服务器端口
        #[arg(long, default_value = "5060")]
        server_port: u16,
        /// SIP用户名
        #[arg(short, long)]
        username: String,
        /// SIP密码
        #[arg(long)]
        password: String,
    },
    /// 拨打电话
    Call {
        /// 目标号码
        #[arg(short, long)]
        number: String,
        /// FreeSWITCH服务器地址
        #[arg(short, long, default_value = "127.0.0.1")]
        server: String,
        /// FreeSWITCH服务器端口
        #[arg(long, default_value = "5060")]
        server_port: u16,
        /// SIP用户名
        #[arg(short, long)]
        username: String,
        /// SIP密码
        #[arg(long)]
        password: String,
    },
    /// 测试SIP消息处理
    Test {
        /// 测试SIP消息
        #[arg(short, long, default_value = "INVITE sip:1000@127.0.0.1 SIP/2.0")]
        message: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SipConfig {
    username: String,
    password: String,
    server: String,
    server_port: u16,
    local_port: u16,
}

#[derive(Debug)]
struct SipClient {
    config: SipConfig,
    call_id: Arc<Mutex<String>>,
    calls: Arc<Mutex<HashMap<String, CallState>>>,
    auth_info: Arc<Mutex<Option<AuthInfo>>>,
    audio_processor: Arc<Mutex<Option<AudioProcessor>>>,
    audio_io: Arc<Mutex<Option<AudioIO>>>,
    stop_audio: Arc<Mutex<bool>>,
}

#[derive(Debug, Clone)]
enum CallState {
    Ringing,
    Connected,
    Disconnected,
}

impl SipClient {
    fn new(config: SipConfig) -> Self {
        Self {
            config,
            call_id: Arc::new(Mutex::new(String::new())),
            calls: Arc::new(Mutex::new(HashMap::new())),
            auth_info: Arc::new(Mutex::new(None)),
            audio_processor: Arc::new(Mutex::new(None)),
            audio_io: Arc::new(Mutex::new(None)),
            stop_audio: Arc::new(Mutex::new(false)),
        }
    }

    async fn start_server(&self) -> Result<()> {
        let addr = format!("0.0.0.0:{}", self.config.local_port);
        let listener = TcpListener::bind(&addr).await?;
        info!("SIP客户端服务器启动在 {}", addr);

        // 主动连接到FreeSWITCH服务器进行注册
        let client = self.clone();
        tokio::spawn(async move {
            if let Err(e) = client.register_with_freeswitch().await {
                error!("注册到FreeSWITCH失败: {}", e);
            } else {
                info!("注册成功，开始监听消息");
            }
        });

        // 等待一段时间让注册完成
        tokio::time::sleep(Duration::from_secs(2)).await;

        loop {
            match listener.accept().await {
                Ok((socket, addr)) => {
                    info!("新的连接来自: {}", addr);
                    let client = self.clone();
                    tokio::spawn(async move {
                        if let Err(e) = client.handle_connection(socket, addr).await {
                            error!("处理连接时出错: {}", e);
                        }
                    });
                }
                Err(e) => {
                    error!("接受连接时出错: {}", e);
                }
            }
        }
    }

    async fn register_with_freeswitch(&self) -> Result<()> {
        let server_addr = format!("{}:{}", self.config.server, self.config.server_port);
        info!("正在连接到FreeSWITCH服务器: {}", server_addr);
        
        let mut stream = TcpStream::connect(&server_addr).await?;
        info!("成功连接到FreeSWITCH服务器");
        
        let mut sip_handler = SipMessageHandler::new(self.config.server.clone());
        
        // 创建REGISTER请求
        let register_request = sip_handler.create_register_request(
            &self.config.username,
            &self.config.password,
            &format!("{}:{}", self.config.server, self.config.local_port)
        );
        
        info!("发送REGISTER请求到FreeSWITCH:");
        info!("{}", register_request);
        
        sip_handler.send_sip_message(&mut stream, &register_request).await?;
        
        // 等待响应
        let mut response_buffer = [0; 4096];
        let mut total_response = String::new();
        
        // 设置超时时间
        let timeout_duration = Duration::from_secs(10);
        let start_time = std::time::Instant::now();
        
        while start_time.elapsed() < timeout_duration {
            match timeout(Duration::from_millis(100), stream.read(&mut response_buffer)).await {
                Ok(Ok(n)) if n > 0 => {
                    let response_chunk = String::from_utf8_lossy(&response_buffer[..n]);
                    total_response.push_str(&response_chunk);
                    
                    // 检查是否收到了完整的SIP响应
                    if total_response.contains("\r\n\r\n") {
                        info!("收到FreeSWITCH响应:");
                        info!("{}", total_response);
                        
                        if let Ok(sip_response) = sip_handler.parse_sip_response(&total_response) {
                            match sip_response.status_code {
                                200 => {
                                    info!("成功注册到FreeSWITCH服务器");
                                    
                                    // 注册成功，等待服务器发送NOTIFY
                                    info!("注册成功，等待服务器发送NOTIFY消息");
                                    
                                    return Ok(());
                                }
                                401 => {
                                    info!("401 Unauthorized - 需要认证");
                                    // 处理认证
                                    if let Err(e) = self.handle_register_auth(&mut stream, &sip_response, &sip_handler).await {
                                        error!("处理注册认证失败: {}", e);
                                        return Err(e);
                                    }
                                    return Ok(());
                                }
                                407 => {
                                    info!("407 Proxy Authentication Required - 需要代理认证");
                                    // 处理代理认证
                                    if let Err(e) = self.handle_register_proxy_auth(&mut stream, &sip_response, &sip_handler).await {
                                        error!("处理代理认证失败: {}", e);
                                        return Err(e);
                                    }
                                    return Ok(());
                                }
                                _ => {
                                    warn!("注册失败，状态码: {}", sip_response.status_code);
                                    return Ok(());
                                }
                            }
                        }
                        break;
                    }
                }
                Ok(Ok(0)) => {
                    info!("连接已关闭");
                    break;
                }
                Ok(Ok(_)) => {
                    continue;
                }
                Ok(Err(e)) => {
                    error!("读取响应时出错: {}", e);
                    break;
                }
                Err(_) => {
                    continue;
                }
            }
        }
        
        if total_response.is_empty() {
            warn!("未收到任何响应，可能连接有问题");
        }
        
        Ok(())
    }

    async fn handle_register_auth(&self, stream: &mut TcpStream, sip_response: &SipResponse, sip_handler: &SipMessageHandler) -> Result<()> {
        info!("处理注册认证");
        
        // 从响应中提取认证信息
        let auth_header = sip_response.headers.get("WWW-Authenticate")
            .context("缺少WWW-Authenticate头部")?;
        
        info!("认证信息: {}", auth_header);
        
        // 解析认证信息
        let auth_info = sip_handler.parse_auth_header(auth_header)?;
        
        // 保存认证信息
        {
            let mut auth_guard = self.auth_info.lock().unwrap();
            *auth_guard = Some(auth_info.clone());
        }
        
        // 生成认证响应
        let auth_response = sip_handler.create_auth_response(
            &auth_info,
            &self.config.username,
            &self.config.password,
            "REGISTER",
            &format!("sip:{};transport=TCP", self.config.username)
        );
        
        // 使用新的认证REGISTER请求方法
        let authenticated_register = sip_handler.create_authenticated_register_request(
            &self.config.username,
            &self.config.password,
            &format!("{}:{}", self.config.server, self.config.local_port),
            &auth_response
        );
        
        info!("重新发送带认证的REGISTER请求:");
        info!("{}", authenticated_register);
        
        sip_handler.send_sip_message(stream, &authenticated_register).await?;
        
        // 等待最终响应
        let mut response_buffer = [0; 4096];
        let mut total_response = String::new();
        
        // 设置超时时间
        let timeout_duration = Duration::from_secs(10);
        let start_time = std::time::Instant::now();
        
        while start_time.elapsed() < timeout_duration {
            match timeout(Duration::from_millis(100), stream.read(&mut response_buffer)).await {
                Ok(Ok(n)) if n > 0 => {
                    let response_chunk = String::from_utf8_lossy(&response_buffer[..n]);
                    total_response.push_str(&response_chunk);
                    
                    // 检查是否收到了完整的SIP响应
                    if total_response.contains("\r\n\r\n") {
                        info!("收到认证后响应:");
                        info!("{}", total_response);
                        
                        if let Ok(sip_response) = sip_handler.parse_sip_response(&total_response) {
                            match sip_response.status_code {
                                200 => {
                                    info!("认证成功，注册完成");
                                    
                                    // 认证成功，等待服务器发送NOTIFY
                                    info!("认证成功，等待服务器发送NOTIFY消息");
                                    
                                    return Ok(());
                                }
                                _ => {
                                    warn!("认证后注册失败，状态码: {}", sip_response.status_code);
                                    return Ok(());
                                }
                            }
                        }
                        break;
                    }
                }
                Ok(Ok(0)) => {
                    info!("连接已关闭");
                    break;
                }
                Ok(Ok(_)) => {
                    continue;
                }
                Ok(Err(e)) => {
                    error!("读取响应时出错: {}", e);
                    break;
                }
                Err(_) => {
                    continue;
                }
            }
        }
        
        Ok(())
    }

    async fn handle_register_proxy_auth(&self, stream: &mut TcpStream, sip_response: &SipResponse, sip_handler: &SipMessageHandler) -> Result<()> {
        info!("处理注册代理认证");
        
        // 从响应中提取认证信息
        let proxy_auth = sip_response.headers.get("Proxy-Authenticate")
            .context("缺少Proxy-Authenticate头部")?;
        
        info!("代理认证信息: {}", proxy_auth);
        
        // 解析认证信息
        let auth_info = sip_handler.parse_auth_header(proxy_auth)?;
        
        // 保存认证信息
        {
            let mut auth_guard = self.auth_info.lock().unwrap();
            *auth_guard = Some(auth_info.clone());
        }
        
        // 生成认证响应
        let auth_response = sip_handler.create_auth_response(
            &auth_info,
            &self.config.username,
            &self.config.password,
            "REGISTER",
            &format!("sip:{}", self.config.username)
        );
        
        // 重新发送带认证的REGISTER请求
        let register_request = sip_handler.create_register_request(
            &self.config.username,
            &self.config.password,
            &format!("{}:{}", self.config.server, self.config.local_port)
        );
        
        let authenticated_register = sip_handler.add_auth_header(&register_request, &auth_response);
        
        info!("重新发送带代理认证的REGISTER请求:");
        info!("{}", authenticated_register);
        
        sip_handler.send_sip_message(stream, &authenticated_register).await?;
        
        // 等待最终响应
        let mut response_buffer = [0; 4096];
        let mut total_response = String::new();
        
        // 设置超时时间
        let timeout_duration = Duration::from_secs(10);
        let start_time = std::time::Instant::now();
        
        while start_time.elapsed() < timeout_duration {
            match timeout(Duration::from_millis(100), stream.read(&mut response_buffer)).await {
                Ok(Ok(n)) if n > 0 => {
                    let response_chunk = String::from_utf8_lossy(&response_buffer[..n]);
                    total_response.push_str(&response_chunk);
                    
                    // 检查是否收到了完整的SIP响应
                    if total_response.contains("\r\n\r\n") {
                        info!("收到代理认证后响应:");
                        info!("{}", total_response);
                        
                        if let Ok(sip_response) = sip_handler.parse_sip_response(&total_response) {
                            match sip_response.status_code {
                                200 => {
                                    info!("代理认证成功，注册完成");
                                    
                                    // 代理认证成功，等待服务器发送NOTIFY
                                    info!("代理认证成功，等待服务器发送NOTIFY消息");
                                    
                                    return Ok(());
                                }
                                _ => {
                                    warn!("代理认证后注册失败，状态码: {}", sip_response.status_code);
                                    return Ok(());
                                }
                            }
                        }
                        break;
                    }
                }
                Ok(Ok(0)) => {
                    info!("连接已关闭");
                    break;
                }
                Ok(Ok(_)) => {
                    continue;
                }
                Ok(Err(e)) => {
                    error!("读取响应时出错: {}", e);
                    break;
                }
                Err(_) => {
                    continue;
                }
            }
        }
        
        Ok(())
    }

    async fn handle_connection(&self, socket: TcpStream, addr: SocketAddr) -> Result<()> {
        let mut sip_handler = SipMessageHandler::new(self.config.server.clone());
        let mut stream = socket;
        
        info!("处理来自 {} 的连接", addr);
        
        let mut message_count = 0;
        loop {
            message_count += 1;
            info!("等待第 {} 个SIP消息...", message_count);
            
            match sip_handler.read_sip_message(&mut stream).await {
                Ok(Some(message)) => {
                    info!("收到SIP消息: {}", message.lines().next().unwrap_or(""));
                    
                    // 尝试解析为请求或响应
                    if let Ok(request) = sip_handler.parse_sip_request(&message) {
                        info!("成功解析SIP请求: {}", request.method);
                        self.handle_sip_request(&request, &mut stream, &sip_handler).await?;
                    } else if let Ok(response) = sip_handler.parse_sip_response(&message) {
                        info!("成功解析SIP响应: {} {}", response.status_code, response.reason_phrase);
                        self.handle_sip_response(&response).await?;
                    } else {
                        warn!("无法解析SIP消息，原始消息长度: {} 字节", message.len());
                        warn!("消息前100字符: {}", &message[..message.len().min(100)]);
                        
                        // 尝试手动处理NOTIFY消息
                        if message.contains("NOTIFY") {
                            info!("检测到NOTIFY消息，尝试手动处理");
                            if let Ok(request) = sip_handler.parse_sip_request(&message) {
                                info!("手动解析NOTIFY成功");
                                self.handle_notify_request(&request, &mut stream, &sip_handler).await?;
                            } else {
                                error!("手动解析NOTIFY失败");
                            }
                        }
                    }
                }
                Ok(None) => {
                    // 检查是否是因为消息不完整而返回None
                    if message_count == 1 {
                        // 第一次读取，可能是消息不完整，继续尝试
                        info!("第一次读取返回None，可能是消息不完整，继续尝试...");
                        continue;
                    } else {
                        info!("连接关闭或超时，退出连接处理循环");
                        break;
                    }
                }
                Err(e) => {
                    error!("读取SIP消息时出错: {}", e);
                    break;
                }
            }
        }
        
        info!("连接处理完成");
        Ok(())
    }

    async fn handle_sip_request(&self, request: &SipRequest, stream: &mut TcpStream, sip_handler: &SipMessageHandler) -> Result<()> {
        match request.method.as_str() {
            "INVITE" => {
                info!("收到INVITE请求");
                self.handle_incoming_call(request, stream, sip_handler).await?;
            }
            "BYE" => {
                info!("收到BYE请求");
                self.handle_hangup_request(request, stream, sip_handler).await?;
            }
            "ACK" => {
                info!("收到ACK请求");
                self.handle_ack_request(request).await?;
            }
            "NOTIFY" => {
                info!("收到NOTIFY请求");
                self.handle_notify_request(request, stream, sip_handler).await?;
            }
            _ => {
                warn!("未处理的SIP方法: {}", request.method);
            }
        }
        Ok(())
    }

    async fn handle_sip_response(&self, response: &SipResponse) -> Result<()> {
        info!("收到SIP响应: {} {}", response.status_code, response.reason_phrase);
        
        match response.status_code {
            200 => {
                info!("呼叫已接通");
                // 启动音频处理
                self.start_audio_session().await?;
            }
            180 => {
                info!("对方正在振铃");
            }
            486 => {
                info!("对方忙线");
            }
            404 => {
                info!("号码不存在");
            }
            _ => {
                warn!("未处理的响应状态: {}", response.status_code);
            }
        }
        
        Ok(())
    }

    async fn handle_incoming_call(&self, request: &SipRequest, stream: &mut TcpStream, sip_handler: &SipMessageHandler) -> Result<()> {
        let call_id = request.headers.get("Call-ID")
            .context("缺少Call-ID头部")?;
        
        info!("收到来电，Call-ID: {}", call_id);
        
        // 更新呼叫状态
        {
            let mut calls_guard = self.calls.lock().unwrap();
            calls_guard.insert(call_id.clone(), CallState::Ringing);
        }

        // 自动接听（在实际应用中可能需要用户确认）
        self.answer_call(request, stream, sip_handler).await?;
        
        Ok(())
    }

    async fn answer_call(&self, request: &SipRequest, stream: &mut TcpStream, sip_handler: &SipMessageHandler) -> Result<()> {
        let call_id = request.headers.get("Call-ID")
            .context("缺少Call-ID头部")?;
        
        info!("接听电话，Call-ID: {}", call_id);
        
        // 构建200 OK响应
        let sdp = sip_handler.create_sdp();
        let response = sip_handler.create_ok_response(request, &sdp);
        
        // 发送响应
        sip_handler.send_sip_message(stream, &response).await?;
        
        // 更新呼叫状态
        {
            let mut calls_guard = self.calls.lock().unwrap();
            calls_guard.insert(call_id.clone(), CallState::Connected);
        }

        info!("电话已接通，开始语音对话");
        
        // 启动音频处理
        self.start_audio_session().await?;
        
        Ok(())
    }

    async fn handle_hangup_request(&self, request: &SipRequest, stream: &mut TcpStream, sip_handler: &SipMessageHandler) -> Result<()> {
        let call_id = request.headers.get("Call-ID")
            .context("缺少Call-ID头部")?;
        
        info!("收到挂断请求，Call-ID: {}", call_id);
        
        // 停止音频传输
        self.stop_audio_transmission().await?;
        
        // 发送200 OK响应
        let response = format!(
            "SIP/2.0 200 OK\r\n\
             From: {}\r\n\
             To: {}\r\n\
             Call-ID: {}\r\n\
             CSeq: {}\r\n\
             \r\n",
            request.headers.get("From").unwrap_or(&"".to_string()),
            request.headers.get("To").unwrap_or(&"".to_string()),
            call_id,
            request.headers.get("CSeq").unwrap_or(&"".to_string())
        );
        
        sip_handler.send_sip_message(stream, &response).await?;
        
        // 更新呼叫状态
        {
            let mut calls_guard = self.calls.lock().unwrap();
            calls_guard.insert(call_id.clone(), CallState::Disconnected);
        }

        info!("电话已挂断");
        
        Ok(())
    }

    async fn handle_ack_request(&self, request: &SipRequest) -> Result<()> {
        let call_id = request.headers.get("Call-ID")
            .context("缺少Call-ID头部")?;
        
        info!("收到ACK确认，Call-ID: {}", call_id);
        
        // 启动音频处理
        self.start_audio_session().await?;
        
        Ok(())
    }

    async fn start_audio_session(&self) -> Result<()> {
        // 这里应该启动音频处理
        // 在实际实现中，需要从SDP中提取RTP地址和端口
        info!("启动音频会话");
        
        // 示例：启动音频处理器
        let rtp_port = self.config.local_port + 1000;
        let mut audio_processor = AudioProcessor::new(
            rtp_port,
            8000, // 采样率
            1,    // 单声道
        ).await?;
        
        // 在实际实现中，需要从SDP中获取远程RTP地址
        // let remote_rtp_addr = "127.0.0.1:10000".parse()?;
        // audio_processor.start_audio_session(remote_rtp_addr).await?;
        
        // 保存音频处理器
        {
            let mut audio_guard = self.audio_processor.lock().unwrap();
            *audio_guard = Some(audio_processor);
        }
        
        Ok(())
    }

    async fn make_call(&self, number: &str) -> Result<()> {
        info!("正在拨打号码: {}", number);
        
        // 连接到FreeSWITCH服务器
        let server_addr = format!("{}:{}", self.config.server, self.config.server_port);
        info!("尝试连接到: {}", server_addr);
        
        let mut stream = TcpStream::connect(&server_addr).await?;
        info!("已连接到FreeSWITCH服务器: {}", server_addr);

        // 生成Call-ID
        let call_id = format!("{}@{}", uuid::Uuid::new_v4(), self.config.server);
        {
            let mut call_id_guard = self.call_id.lock().unwrap();
            *call_id_guard = call_id.clone();
        }

        // 构建INVITE请求
        let sip_handler = SipMessageHandler::new(self.config.server.clone());
        let target_uri = format!("sip:{}@{};transport=TCP", number, self.config.server);
        let from_uri = format!("sip:{}@{};transport=TCP", self.config.username, self.config.server);
        let contact = format!("sip:{}@{}:{};transport=tcp", self.config.username, self.config.server, self.config.local_port);
        
        let mut invite_message = sip_handler.create_invite_request(&target_uri, &from_uri, &call_id, &contact);
        
        // 如果有保存的认证信息，添加到INVITE请求中
        {
            let auth_guard = self.auth_info.lock().unwrap();
            if let Some(ref auth_info) = *auth_guard {
                info!("使用已保存的认证信息");
                let auth_response = sip_handler.create_auth_response(
                    auth_info,
                    &self.config.username,
                    &self.config.password,
                    "INVITE",
                    &target_uri
                );
                invite_message = sip_handler.add_auth_header(&invite_message, &auth_response);
            } else {
                info!("没有保存的认证信息，将发送不带认证的INVITE");
            }
        }
        
        info!("发送INVITE请求:");
        info!("{}", invite_message);
        
        // 发送INVITE请求
        info!("正在发送INVITE请求...");
        sip_handler.send_sip_message(&mut stream, &invite_message).await?;
        info!("INVITE请求发送完成");
        
        info!("INVITE请求已发送，Call-ID: {}", call_id);
        
        // 更新呼叫状态
        {
            let mut calls_guard = self.calls.lock().unwrap();
            calls_guard.insert(call_id.clone(), CallState::Ringing);
        }

        // 等待并处理响应
        let mut response_buffer = [0; 4096];
        let mut total_response = String::new();
        let mut cseq = 1;
        let mut need_auth = false;
        let mut auth_info = None;
        
        // 设置超时时间
        let timeout_duration = Duration::from_secs(30); // 增加超时时间
        let start_time = std::time::Instant::now();
        
        info!("开始等待响应...");
        info!("按 Ctrl+C 可以取消呼叫");
        
        while start_time.elapsed() < timeout_duration {
            match timeout(Duration::from_millis(100), stream.read(&mut response_buffer)).await {
                Ok(Ok(n)) if n > 0 => {
                    info!("收到 {} 字节数据", n);
                    let response_chunk = String::from_utf8_lossy(&response_buffer[..n]);
                    total_response.push_str(&response_chunk);
                    
                    // 检查是否收到了完整的SIP响应
                    if total_response.contains("\r\n\r\n") {
                        info!("收到完整响应:");
                        info!("{}", total_response);
                        
                        // 解析响应
                        if let Ok(sip_response) = sip_handler.parse_sip_response(&total_response) {
                            match sip_response.status_code {
                                100 => {
                                    info!("100 Trying - 请求正在处理");
                                    // 继续等待更多响应
                                    total_response.clear();
                                    continue;
                                }
                                180 => {
                                    info!("180 Ringing - 对方正在振铃");
                                    // 继续等待更多响应
                                    total_response.clear();
                                    continue;
                                }
                                183 => {
                                    info!("183 Session Progress - 会话进展");
                                    // 继续等待更多响应
                                    total_response.clear();
                                    continue;
                                }
                                200 => {
                                    info!("200 OK - 呼叫已接通");
                                    
                                    // 解析SDP获取RTP信息
                                    let sdp_info = if let Some(body) = &sip_response.body {
                                        let sdp_body = String::from_utf8_lossy(body);
                                        info!("收到SDP: {}", sdp_body);
                                        sip_handler.parse_sdp(&sdp_body)?
                                    } else {
                                        return Err(anyhow::anyhow!("200 OK响应中没有SDP信息"));
                                    };
                                    
                                    info!("解析到RTP地址: {}:{}", sdp_info.remote_ip, sdp_info.remote_port);
                                    
                                    // 发送ACK
                                    self.send_ack(&mut stream, &sip_response, &sip_handler).await?;
                                    
                                    // 更新呼叫状态
                                    {
                                        let mut calls_guard = self.calls.lock().unwrap();
                                        calls_guard.insert(call_id.clone(), CallState::Connected);
                                    }
                                    
                                    info!("呼叫已建立，开始音频会话...");
                                    
                                    // 启动音频会话
                                    self.start_audio_session_with_rtp(&sdp_info).await?;
                                    
                                    // 保持连接以维持通话
                                    info!("通话已建立，按 Ctrl+C 结束通话");
                                    loop {
                                        tokio::time::sleep(Duration::from_secs(1)).await;
                                    }
                                }
                                401 => {
                                    error!("401 Unauthorized - 需要认证");
                                    need_auth = true;
                                    break;
                                }
                                407 => {
                                    error!("407 Proxy Authentication Required - 需要代理认证");
                                    need_auth = true;
                                    // 解析认证信息
                                    if let Some(auth_header) = sip_response.headers.get("Proxy-Authenticate") {
                                        auth_info = Some(sip_handler.parse_auth_header(auth_header)?);
                                    }
                                    break;
                                }
                                404 => {
                                    error!("404 Not Found - 号码不存在");
                                    break;
                                }
                                486 => {
                                    error!("486 Busy Here - 对方忙线");
                                    break;
                                }
                                487 => {
                                    error!("487 Request Terminated - 请求被终止");
                                    break;
                                }
                                _ => {
                                    warn!("收到状态码: {} - {}", sip_response.status_code, sip_response.reason_phrase);
                                    // 继续等待更多响应
                                    total_response.clear();
                                    continue;
                                }
                            }
                        }
                        break;
                    }
                }
                Ok(Ok(0)) => {
                    info!("连接已关闭");
                    break;
                }
                Ok(Ok(_)) => {
                    continue;
                }
                Ok(Err(e)) => {
                    error!("读取响应时出错: {}", e);
                    break;
                }
                Err(_) => {
                    // 超时，继续等待
                    continue;
                }
            }
        }
        
        // 如果需要认证，重新发送带认证的INVITE
        if need_auth {
            if let Some(auth) = auth_info {
                info!("重新发送带认证的INVITE请求");
                cseq += 1;
                
                // 保存认证信息
                {
                    let mut auth_guard = self.auth_info.lock().unwrap();
                    *auth_guard = Some(auth.clone());
                }
                
                // 创建带认证的INVITE
                let auth_response = sip_handler.create_auth_response(
                    &auth,
                    &self.config.username,
                    &self.config.password,
                    "INVITE",
                    &target_uri
                );
                
                let mut authenticated_invite = sip_handler.create_invite_request(&target_uri, &from_uri, &call_id, &contact);
                authenticated_invite = sip_handler.add_auth_header(&authenticated_invite, &auth_response);
                
                // 更新CSeq
                authenticated_invite = authenticated_invite.replace("CSeq: 1 INVITE", &format!("CSeq: {} INVITE", cseq));
                
                info!("发送带认证的INVITE请求:");
                info!("{}", authenticated_invite);
                
                sip_handler.send_sip_message(&mut stream, &authenticated_invite).await?;
                
                // 继续等待响应
                total_response.clear();
                let auth_start_time = std::time::Instant::now();
                
                while auth_start_time.elapsed() < Duration::from_secs(20) {
                    match timeout(Duration::from_millis(100), stream.read(&mut response_buffer)).await {
                        Ok(Ok(n)) if n > 0 => {
                            let response_chunk = String::from_utf8_lossy(&response_buffer[..n]);
                            total_response.push_str(&response_chunk);
                            
                            if total_response.contains("\r\n\r\n") {
                                info!("收到认证后的响应:");
                                info!("{}", total_response);
                                
                                if let Ok(sip_response) = sip_handler.parse_sip_response(&total_response) {
                                    match sip_response.status_code {
                                        100 => {
                                            info!("100 Trying - 认证后请求正在处理");
                                            // 继续等待更多响应
                                            total_response.clear();
                                            continue;
                                        }
                                        180 => {
                                            info!("180 Ringing - 对方正在振铃");
                                            // 继续等待更多响应
                                            total_response.clear();
                                            continue;
                                        }
                                        183 => {
                                            info!("183 Session Progress - 会话进展");
                                            // 继续等待更多响应
                                            total_response.clear();
                                            continue;
                                        }
                                        200 => {
                                            info!("200 OK - 认证后呼叫已接通");
                                            
                                            // 解析SDP获取RTP信息
                                            let sdp_info = if let Some(body) = &sip_response.body {
                                                let sdp_body = String::from_utf8_lossy(body);
                                                info!("收到SDP: {}", sdp_body);
                                                sip_handler.parse_sdp(&sdp_body)?
                                            } else {
                                                return Err(anyhow::anyhow!("200 OK响应中没有SDP信息"));
                                            };
                                            
                                            info!("解析到RTP地址: {}:{}", sdp_info.remote_ip, sdp_info.remote_port);
                                            
                                            self.send_ack(&mut stream, &sip_response, &sip_handler).await?;
                                            
                                            {
                                                let mut calls_guard = self.calls.lock().unwrap();
                                                calls_guard.insert(call_id.clone(), CallState::Connected);
                                            }
                                            
                                            info!("呼叫已建立，开始音频会话...");
                                            
                                            // 启动音频会话
                                            self.start_audio_session_with_rtp(&sdp_info).await?;
                                            
                                            // 保持连接以维持通话
                                            info!("通话已建立，按 Ctrl+C 结束通话");
                                            loop {
                                                tokio::time::sleep(Duration::from_secs(1)).await;
                                            }
                                        }
                                        _ => {
                                            warn!("认证后收到状态码: {} - {}", sip_response.status_code, sip_response.reason_phrase);
                                        }
                                    }
                                }
                                break;
                            }
                        }
                        Ok(Ok(0)) => {
                            info!("认证后连接已关闭");
                            break;
                        }
                        Ok(Ok(_)) => continue,
                        Ok(Err(e)) => {
                            error!("认证后读取响应时出错: {}", e);
                            break;
                        }
                        Err(_) => continue,
                    }
                }
            }
        }
        
        if total_response.is_empty() {
            warn!("未收到任何响应，可能连接有问题");
            info!("总等待时间: {:?}", start_time.elapsed());
        }

        Ok(())
    }

    async fn cancel_call(&self, call_id: &str) -> Result<()> {
        info!("正在取消呼叫: {}", call_id);
        
        // 连接到FreeSWITCH服务器
        let server_addr = format!("{}:{}", self.config.server, self.config.server_port);
        let mut stream = TcpStream::connect(&server_addr).await?;
        
        let sip_handler = SipMessageHandler::new(self.config.server.clone());
        let target_uri = format!("sip:{}@{};transport=TCP", "1001", self.config.server);
        
        // 创建CANCEL请求
        let cancel_message = sip_handler.create_cancel_request(&target_uri, call_id, "2");
        
        info!("发送CANCEL请求:");
        info!("{}", cancel_message);
        
        // 发送CANCEL请求
        sip_handler.send_sip_message(&mut stream, &cancel_message).await?;
        
        // 更新呼叫状态
        {
            let mut calls_guard = self.calls.lock().unwrap();
            calls_guard.insert(call_id.to_string(), CallState::Disconnected);
        }
        
        info!("CANCEL请求已发送");
        Ok(())
    }

    async fn test_connection(&self) -> Result<()> {
        info!("测试SIP连接到: {}:{}", self.config.server, self.config.server_port);
        
        // 连接到FreeSWITCH服务器
        let server_addr = format!("{}:{}", self.config.server, self.config.server_port);
        info!("尝试连接到: {}", server_addr);
        
        let mut stream = TcpStream::connect(&server_addr).await?;
        info!("已连接到FreeSWITCH服务器: {}", server_addr);

        // 简单测试：发送一个最基本的SIP消息
        let simple_message = format!(
            "OPTIONS sip:{} SIP/2.0\r\nCall-ID: test@127.0.0.1\r\nCSeq: 1 OPTIONS\r\nFrom: <sip:1000@{}>\r\nTo: <sip:{}>\r\nVia: SIP/2.0/TCP 127.0.0.1:5060\r\n\r\n",
            self.config.server, self.config.server, self.config.server
        );
        
        info!("发送最简单的OPTIONS请求:");
        info!("{}", simple_message);
        
        // 发送消息
        stream.write_all(simple_message.as_bytes()).await?;
        stream.flush().await?;
        info!("消息发送完成");
        
        // 等待响应
        let mut response_buffer = [0; 1024];
        match timeout(Duration::from_secs(5), stream.read(&mut response_buffer)).await {
            Ok(Ok(n)) => {
                if n > 0 {
                    let response = String::from_utf8_lossy(&response_buffer[..n]);
                    info!("收到响应 ({} 字节):", n);
                    info!("{}", response);
                } else {
                    info!("连接已关闭");
                }
            }
            Ok(Err(e)) => {
                error!("读取响应时出错: {}", e);
            }
            Err(_) => {
                warn!("等待响应超时");
            }
        }

        Ok(())
    }

    async fn send_ack(&self, stream: &mut TcpStream, sip_response: &SipResponse, sip_handler: &SipMessageHandler) -> Result<()> {
        let call_id = sip_response.headers.get("Call-ID")
            .context("缺少Call-ID头部")?;
        
        let ack_message = sip_handler.create_ack_request(call_id);
        sip_handler.send_sip_message(stream, &ack_message).await?;
        info!("发送ACK请求，Call-ID: {}", call_id);
        
        Ok(())
    }

    async fn handle_notify_request(&self, request: &SipRequest, stream: &mut TcpStream, sip_handler: &SipMessageHandler) -> Result<()> {
        let call_id = request.headers.get("Call-ID")
            .context("缺少Call-ID头部")?;
        
        info!("收到NOTIFY请求，Call-ID: {}", call_id);
        
        // 按照SIP标准处理NOTIFY的三个部分
        // 1. Request-Line: NOTIFY sip:xxx SIP/2.0
        info!("Request-Line: {} {} {}", request.method, request.uri, request.version);
        
        // 2. Message Header: 检查关键头部
        let content_type = request.headers.get("Content-Type").map_or("", |v| v).to_string();
        let event = request.headers.get("Event").map_or("", |v| v).to_string();
        let messages_waiting = request.headers.get("Messages-Waiting").map_or("", |v| v).to_string();
        let subscription_state = request.headers.get("Subscription-State").map_or("", |v| v).to_string();
        
        info!("Message Header:");
        info!("  Content-Type: {}", content_type);
        info!("  Event: {}", event);
        info!("  Messages-Waiting: {}", messages_waiting);
        info!("  Subscription-State: {}", subscription_state);
        
        // 3. Message Body: 处理消息体
        if let Some(body) = &request.body {
            let body_str = String::from_utf8_lossy(body);
            if !body_str.is_empty() {
                info!("Message Body: {}", body_str);
            }
        }
        
        // 处理消息等待通知
        if !messages_waiting.is_empty() {
            if messages_waiting == "yes" {
                info!("有新消息等待");
            } else {
                info!("没有新消息等待");
            }
        }
        
        // 发送200 OK响应
        let response = format!(
            "SIP/2.0 200 OK\r\n\
             Via: {}\r\n\
             From: {}\r\n\
             To: {}\r\n\
             Call-ID: {}\r\n\
             CSeq: {}\r\n\
             User-Agent: Z 5.6.10 v2.10.20.10\r\n\
             Content-Length: 0\r\n\
             \r\n",
            request.headers.get("Via").map_or("", |v| v),
            request.headers.get("From").map_or("", |v| v),
            request.headers.get("To").map_or("", |v| v),
            call_id,
            request.headers.get("CSeq").map_or("", |v| v)
        );
        
        sip_handler.send_sip_message(stream, &response).await?;
        info!("已发送NOTIFY 200 OK响应");
        
        Ok(())
    }

    async fn start_audio_session_with_rtp(&self, sdp_info: &SdpInfo) -> Result<()> {
        info!("启动音频会话，远程RTP地址: {}:{}", sdp_info.remote_ip, sdp_info.remote_port);
        
        // 重置停止标志
        {
            let mut stop_guard = self.stop_audio.lock().unwrap();
            *stop_guard = false;
        }
        
        // 创建音频处理器
        let rtp_port = self.config.local_port + 1000;
        let mut audio_processor = AudioProcessor::new(
            rtp_port,
            8000, // 采样率
            1,    // 单声道
        ).await?;
        
        // 设置远程RTP地址
        let remote_rtp_addr = format!("{}:{}", sdp_info.remote_ip, sdp_info.remote_port).parse()?;
        audio_processor.start_audio_session(remote_rtp_addr).await?;
        
        info!("音频会话已启动，本地RTP端口: {}", rtp_port);
        
        // 保存音频处理器
        {
            let mut audio_guard = self.audio_processor.lock().unwrap();
            *audio_guard = Some(audio_processor);
        }
        
        // 直接启动音频传输（在主线程中）
        self.start_audio_transmission_main_thread().await?;
        
        Ok(())
    }

    async fn start_audio_transmission_main_thread(&self) -> Result<()> {
        info!("开始音频传输...");
        
        // 启动音频IO
        let mut audio_io = AudioIO::new(8000, 1)?;
        audio_io.start()?;
        
        // 保存音频IO
        {
            let mut audio_io_guard = self.audio_io.lock().unwrap();
            *audio_io_guard = Some(audio_io);
        }
        
        let mut frame_count = 0;
        let mut silence_count = 0;
        
        // 创建20ms间隔的定时器，确保音频包发送的规律性
        let mut interval = tokio::time::interval(Duration::from_millis(20));
        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
        
        loop {
            // 等待下一个20ms间隔
            interval.tick().await;
            // 检查是否需要停止
            if *self.stop_audio.lock().unwrap() {
                info!("收到停止音频传输信号，退出音频传输循环");
                break;
            }
            
            // 获取音频处理器
            let mut audio_processor = {
                let mut audio_guard = self.audio_processor.lock().unwrap();
                audio_guard.take()
            };
            
            if let Some(mut audio_processor) = audio_processor {
                // 获取麦克风输入数据
                let audio_data = {
                    let mut audio_io_guard = self.audio_io.lock().unwrap();
                    if let Some(ref mut audio_io) = *audio_io_guard {
                        audio_io.get_input_data()
                    } else {
                        None
                    }
                };
                
                // 准备要发送的音频数据
                let (pcmu_data, has_audio) = if let Some(input_data) = audio_data {
                    // 确保数据长度正确（应该已经是160个样本）
                    if input_data.len() == 160 {
                        let avg_volume = input_data.iter().map(|x| x.abs()).sum::<f32>() / input_data.len() as f32;
                        let has_audio = avg_volume > 0.002; // 进一步降低阈值，捕获更多轻声
                        
                        // 编码为PCMU
                        let pcmu_data = f32_to_pcmu(&input_data);
                        
                        // 调试信息
                        if frame_count % 50 == 0 {
                            let max_volume = input_data.iter().map(|x| x.abs()).fold(0.0, f32::max);
                            debug!("音频帧 {}: 样本数={}, 平均音量={:.4}, 最大音量={:.4}, 有音频={}", 
                                   frame_count, input_data.len(), avg_volume, max_volume, has_audio);
                        }
                        
                        (pcmu_data, has_audio)
                    } else {
                        warn!("音频数据长度不正确: {} (期望160)", input_data.len());
                        (vec![0x7F; 160], false) // PCMU静音
                    }
                } else {
                    // 没有音频数据，发送静音
                    (vec![0x7F; 160], false) // 标准PCMU静音值
                };
                
                // 发送音频数据
                if has_audio {
                    if frame_count % 25 == 0 { // 每500ms报告一次有音频
                        info!("发送有效音频数据: {} 字节", pcmu_data.len());
                    }
                    silence_count = 0; // 重置静音计数
                } else {
                    silence_count += 1;
                    if silence_count % 100 == 0 { // 每2秒报告一次静音
                        debug!("发送静音数据 (连续 {} 帧)", silence_count);
                    }
                }
                
                if let Err(e) = audio_processor.send_audio(&pcmu_data).await {
                    warn!("发送音频数据失败: {}", e);
                }
                
                // 尝试接收音频数据
                match audio_processor.receive_audio().await {
                    Ok(Some(received_audio)) => {
                        info!("接收到 {} 字节音频数据", received_audio.len());
                        
                        // 将接收到的PCMU音频数据转换为f32格式并播放
                        let mut audio_io_guard = self.audio_io.lock().unwrap();
                        if let Some(ref mut audio_io) = *audio_io_guard {
                            let f32_audio = pcmu_to_f32(&received_audio);
                            if let Err(e) = audio_io.send_output_data(f32_audio) {
                                warn!("播放音频数据失败: {}", e);
                            }
                        }
                    }
                    Ok(None) => {
                        // 没有接收到数据，这是正常的
                    }
                    Err(e) => {
                        warn!("接收音频数据失败: {}", e);
                    }
                }
                
                // 重新保存音频处理器
                let mut audio_guard = self.audio_processor.lock().unwrap();
                *audio_guard = Some(audio_processor);
            }
            
            frame_count += 1;
            
            if frame_count % 250 == 0 { // 每5秒报告一次
                info!("已传输 {} 帧音频数据 ({} 秒), 静音帧: {}", frame_count, frame_count / 50, silence_count);
            }
        }
        
        // 停止音频IO
        {
            let mut audio_io_guard = self.audio_io.lock().unwrap();
            if let Some(ref mut audio_io) = *audio_io_guard {
                audio_io.stop();
            }
        }
        
        info!("音频传输已停止");
        Ok(())
    }

    async fn stop_audio_transmission(&self) -> Result<()> {
        info!("停止音频传输...");
        
        // 设置停止标志
        {
            let mut stop_guard = self.stop_audio.lock().unwrap();
            *stop_guard = true;
        }
        
        // 清理音频处理器
        {
            let mut audio_guard = self.audio_processor.lock().unwrap();
            *audio_guard = None;
        }
        
        info!("音频传输已停止");
        Ok(())
    }


}

impl Clone for SipClient {
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            call_id: Arc::clone(&self.call_id),
            calls: Arc::clone(&self.calls),
            auth_info: Arc::clone(&self.auth_info),
            audio_processor: Arc::clone(&self.audio_processor),
            audio_io: Arc::clone(&self.audio_io),
            stop_audio: Arc::clone(&self.stop_audio),
        }
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt::init();

    let matches = clap::Command::new("FreeSWITCH SIP CLI")
        .version("1.0")
        .about("FreeSWITCH SIP客户端")
        .subcommand(
            clap::Command::new("start")
                .about("启动SIP客户端服务器")
                .arg(clap::Arg::new("port").short('p').long("port").default_value("5061"))
                .arg(clap::Arg::new("server").required(true))
                .arg(clap::Arg::new("server-port").long("server-port").default_value("5060"))
                .arg(clap::Arg::new("username").required(true))
                .arg(clap::Arg::new("password").required(true)),
        )
        .subcommand(
            clap::Command::new("call")
                .about("拨打电话")
                .arg(clap::Arg::new("number").required(true))
                .arg(clap::Arg::new("server").required(true))
                .arg(clap::Arg::new("server-port").long("server-port").default_value("5060"))
                .arg(clap::Arg::new("username").required(true))
                .arg(clap::Arg::new("password").required(true)),
        )
        .subcommand(
            clap::Command::new("test")
                .about("测试SIP连接")
                .arg(clap::Arg::new("server").required(true))
                .arg(clap::Arg::new("server-port").long("server-port").default_value("5060")),
        )
        .get_matches();

    match matches.subcommand() {
        Some(("start", sub_matches)) => {
            let port = sub_matches.get_one::<String>("port").unwrap().parse::<u16>()?;
            let server = sub_matches.get_one::<String>("server").unwrap();
            let server_port = sub_matches.get_one::<String>("server-port").unwrap().parse::<u16>()?;
            let username = sub_matches.get_one::<String>("username").unwrap();
            let password = sub_matches.get_one::<String>("password").unwrap();

            let config = SipConfig {
                local_port: port,
                server: server.clone(),
                server_port,
                username: username.clone(),
                password: password.clone(),
            };

            // 启动服务器
            let client = SipClient::new(config);
            
            // 在后台注册到FreeSWITCH
            let client_clone = client.clone();
            tokio::spawn(async move {
                if let Err(e) = client_clone.register_with_freeswitch().await {
                    error!("注册到FreeSWITCH失败: {}", e);
                } else {
                    info!("成功注册到FreeSWITCH");
                }
            });
            
            client.start_server().await?;
        }
        Some(("call", sub_matches)) => {
            let number = sub_matches.get_one::<String>("number").unwrap();
            let server = sub_matches.get_one::<String>("server").unwrap();
            let server_port = sub_matches.get_one::<String>("server-port").unwrap().parse::<u16>()?;
            let username = sub_matches.get_one::<String>("username").unwrap();
            let password = sub_matches.get_one::<String>("password").unwrap();

            let config = SipConfig {
                local_port: 5061,
                server: server.clone(),
                server_port,
                username: username.clone(),
                password: password.clone(),
            };

            let client = SipClient::new(config);
            client.make_call(number).await?;
            
            // 保持程序运行一段时间以维持连接
            tokio::time::sleep(Duration::from_secs(30)).await;
        }
        Some(("test", sub_matches)) => {
            let server = sub_matches.get_one::<String>("server").unwrap();
            let server_port = sub_matches.get_one::<String>("server-port").unwrap().parse::<u16>()?;

            let config = SipConfig {
                local_port: 5061,
                server: server.clone(),
                server_port,
                username: "1000".to_string(),
                password: "1234".to_string(),
            };

            let client = SipClient::new(config);
            client.test_connection().await?;
        }
        _ => {
            println!("请使用 start, call 或 test 子命令");
        }
    }

    Ok(())
}
